package com.hwua.util;


import org.apache.commons.dbcp2.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.beans.beancontext.BeanContext;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 数据库连接工具类
 * @author admin
 */
public class ConnectionTools {
    private  Connection connection;
    /**
     * 内部枚举类实现单例
     */
    public enum GetConnection{
        //实例
        INSTANCE;
        private ConnectionTools connectionTools;
        public ConnectionTools getInstance(){
            if(connectionTools==null){
                connectionTools = new ConnectionTools();
            }
            return connectionTools;
        }
    }
    /**
     * 获取连接的方法
     * @return
     * @throws Exception
     */
    public  Connection getConnection() throws Exception {

            //提供properties对象
            Properties properties = new Properties();
            //加载配置文件
            try {
                properties.load(ConnectionTools.class.getClassLoader().getResourceAsStream("dbcp.properties"));
                //通过静态工厂获取DataSource对象
                DataSource ds = BasicDataSourceFactory.createDataSource(properties);
                //通过DataSource获取连接
                connection = ds.getConnection();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

        return connection;
    }

    /**
     * 关闭结果集
     */
    public void closeResultSet(ResultSet rSet){
        try {
           if(rSet!=null && !rSet.isClosed()){
               rSet.close();
           }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    /**
     * 关闭预处理
     */
    public void closePreparedStatement(PreparedStatement statement){
        try {
            if(statement!=null && !statement.isClosed()){
                statement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    /**
     * 关闭连接
     */
    public void closeConnection(Connection connection){
        try {
            if(connection!=null && !connection.isClosed()){
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
